<template>
  <div>
    <div class="creativeSetup">
      <!-- 素材选项卡 -->
      <div class="display-flex">
        <div 
          v-for="(creative,$index) in creatives"
          :key="$index"
          @click="switchMaterial($index,creative.type)"
          :class="['card', materialIndex === $index ? 'activ-card' : '']"
        > 
          <a-icon type="info-circle" class="card-err" v-if=" cardErr[$index].length !== 0 ? true : false " />
          <div v-if="creative.materials.length > 0 ? true : false" class="card-compute-num">{{ creative.materials.length }}</div>
          <img :src="creative.img">
          <span class="card-name">{{ creative.name }}</span>
          <a-badge :count="creative.length" />
        </div>
      </div>

      <div v-if="creatives[materialIndex].materials.length > 0" class="creativeSetup-content">   
        <a-tabs
          type="editable-card"
          @edit="addCreative"
          @change="tagsChange"
        >
          <a-tab-pane
            v-for="(item,index) in creatives[materialIndex].materials"
            :key="index"
          >
            <!-- :tab="item.tagsName" -->
            <span slot="tab">
              {{ item.tagsName }}
              <a-icon type="info-circle" style="color:red;" class="card-err" v-if=" cardErr[materialIndex].indexOf(index) !== -1 ? true : false " />
            </span>
            <div class="creativeSetup-content-material">
              <!-- 图片素材 -->
              <div v-if="creatives[materialIndex].type === 'image'" class="material-image">
                <img v-if="item.materialItem" :src="item.materialItem ? item.materialItem.url : ''" alt="">
                <a-button
                  @click="addMaterial(creatives[materialIndex].image_mode,creatives[materialIndex].type,creatives[materialIndex].vh,Object.keys(item.materialItem).length !== 0 ? 'replace' : '')"
                  class="image-btn"
                  type="primary"
                  size="small"
                  :icon=" item.materialItem ? 'redo' : 'plus'"
                >
                  {{ Object.keys(item.materialItem).length !== 0 ? '更改素材' : '添加素材' }}
                </a-button>
              </div>
              <!-- 视频素材 -->
              <div v-if="creatives[materialIndex].type === 'video'" class="material-video">
                <div class="video-dome">
                  <img v-if="item.materialItem" :src="item.materialItem ? item.materialItem.poster_url : ''" alt="">
                  <a-button
                    @click="addMaterial(creatives[materialIndex].image_mode,creatives[materialIndex].type,creatives[materialIndex].vh,Object.keys(item.materialItem).length !== 0 ? 'replace' : '')"
                    class="video-btn"
                    :icon=" item.materialItem ? 'redo' : 'plus'"
                    type="primary"
                    size="small"
                  >
                    {{ Object.keys(item.materialItem).length !== 0 ? '更换素材' : '选择素材' }}
                  </a-button>
                </div>
                <div class="video-cover">
                  <img v-if="item.coverImage" :src="item.coverImage ? item.coverImage.url : ''" alt="">
                  <a-button
                    class="video-btn"
                    :icon=" item.coverImage ? 'redo' : 'plus'"
                    type="primary"
                    size="small"
                    @click="replaceCover(creatives[materialIndex].materials[index].materialItem,creatives[materialIndex].vh,index)"
                  >
                    {{ item.coverImage ? '更换' : '选择' }}封面
                  </a-button>
                </div>
              </div>
            </div>
            <!-- 自定义标题 -->
            <div v-if="creativeMaterialMode === 'no'" class="ivu-collapse-item">
              <div class="ivu-collapse-item-title">
                <a-input placeholder="填写标题,重复填写覆盖" v-model="titleValue" @blur="addTitle(index)" @keyup.enter.native="addTitle(index)" />
                <div style="width:80px;padding:5px 10px;text-align: center;">
                  <span :style="{ 'color':Math.ceil($getStringWidth(titleValue)/2) > 30 ? 'red' : '' }" >{{ Math.ceil($getStringWidth(titleValue)/2) }} </span> / <span>30</span>
                </div>
              </div>
              <div v-if="item.titleList.length !== 0">
                <a-list item-layout="horizontal" :data-source="item.titleList">
                  <a-list-item slot="renderItem" slot-scope="item">
                    {{ item }}
                  </a-list-item>
                </a-list>
              </div>
            </div>

          </a-tab-pane>
        </a-tabs>
        <!-- 程序化标题 -->
        <div v-if="creativeMaterialMode === 'STATIC_ASSEMBLE'" class="ivu-collapse-item">
          <div class="ivu-collapse-item-title">
            <a-input placeholder="填写标题,重复填写覆盖" v-model="titleValue" @keyup.enter.native="addTitles" :suffix="`${Math.ceil($getStringWidth(titleValue)/2)} / 30`" />
            <a-button style="margin: 5px 10px;" type="primary" size="small" icon="plus" @click="addTitles">
              添加标题
            </a-button>
          </div>
          <div v-if="titleList.length !== 0">
            <a-list item-layout="horizontal" :data-source="titleList">
              <a-list-item slot="renderItem" slot-scope="item,index">
                <a-icon slot="actions" type="delete" @click="deleteTitles(index)"/>
                {{ item }}
              </a-list-item>
            </a-list>
          </div>
        </div>
      </div>
      <div v-else class="no-materials">
        <a-button type="primary" icon="plus" @click="addCreative(null,'add')">添加创意</a-button>
      </div>
    </div>
    <!-- 素材库 -->
    <material-item-select
      v-if="is_selectMaterial"
      :optionalNumber="optionalNumber"
      :selectMaterialratio='selectMaterialratio'
      :materialType="materialType"
      :vhType="vhType"
      @closeModal="closeModal"
      @confirmAddMaterial="confirmAddMaterial"
    ></material-item-select>
    <!-- 视频封面选择 -->
    <video-cover
      v-if="is_videoCover"
      :vhType="vhType"
      :videoConf="videoConf"
      @confirmReplaceCover="confirmReplaceCover"
      @closeModal="closeModal"
    ></video-cover>

  </div>
</template>

<script>
export default {
  components:{ 
    materialItemSelect:() => import('./materialItemSelect'),
    videoCover:() => import('./videoCover')
  },
  props:{
    value:{
      type:Array,
      require:true
    },
    creativeNumber:{ // 创意个数
      type:Number
    },
    creativeTotal:{ // 创意总数
      type:Number
    },
    imageCreativeNumber:{ // 图片创意个数
      type:Number
    },
    imageCreativeTotal:{ // 图片创意总数
      type:Number
    },
    videoCreativeNumber:{ // 视频创意个数
      type:Number
    },
    videoCreativeTotal:{ // 视频创意总数
      type:Number
    },
    creativeMaterialMode:{  // 是否程序化
      type:String
    },
    staticTitleList:{  // 是否程序化
      type:Array
    },
  },
  data(){
    return {
      creatives:this.value,
      
      cardErr:{ 0:[], 1:[], 2:[], 3:[], 4:[] },  // 未选择素材提示

      titleList:[], // 标题(程序化)
      materialIndex:0,  // 素材选项
      creativesIndex:0,  // 创意index

      is_selectMaterial:false,
      is_videoCover:false,
      videoConf:'',  // 当前的视频 (更换封面)

      titleValue:'', //标题
      selectMaterialratio:'', // 素材筛选比率(类型：小、横、竖)
      materialType:'', // 判断图片视频类型
      vhType:'', // 判断素材类型 （vertical/horizontal）
      optionalNumber:10,  // 素材库可选择素材数限制

      videoOrImage:'image',// 判断素材类型 （image/video）
      videoCreativeNumberItem:this.videoCreativeNumber, // 程序化时，视频、图片分开计算
      imageCreativeNumberItem:this.imageCreativeNumber,
      creativesNumberItem:this.creativeNumber,//创意个数
    }
  },
  watch:{
    creatives:{
      deep:true,
      handler(params){
        this.$emit('input',params)
        // 自动检测创意素材
        // if( this.cardErr[0].length === 0 && this.cardErr[1].length === 0 && this.cardErr[2].length === 0 && this.cardErr[3].length === 0 && this.cardErr[4].length === 0 ) return
        // for (const key in this.cardErr) {
        //   if( this.cardErr[key].length === 0 ) continue;
        //   params[key].materials.forEach((material,index) => {
        //     let indexs = this.cardErr[key].indexOf(index)
        //     if( indexs === -1 ) return
        //     if( Object.keys(material.materialItem).length !== 0 ){
        //       if( material.materialItem.material_type === 'video' && material.titleList.length !== 0 && material.tagsName && Object.keys(material.coverImage).length !== 0 ) return this.cardErr[key].splice(indexs,1)
        //       if( material.titleList.length !== 0 && material.tagsName ) return this.cardErr[key].splice(indexs,1)
        //     }
        //   });
        // }
      }
    },
    // 监听创意个数
    creativesNumberItem:function (params) {
      this.$emit('update:creativeNumber',params)
    },
    // 监听是否程序化 （清空数据）
    creativeMaterialMode:function (params) {
      if( params == 'STATIC_ASSEMBLE' ){
        let num = this.videoCreativeTotal+this.imageCreativeTotal
        this.$emit('update:creativeTotal',num)
      }else {
        this.$emit('update:creativeTotal',10)
      }
      // 将限制创意个数清空
      this.$emit('update:creativeNumber',0)
      this.$emit('update:imageCreativeNumber',0)
      this.$emit('update:videoCreativeNumber',0)
      this.creativesNumberItem = 0
      this.videoCreativeNumberItem = 0
      this.imageCreativeNumberItem = 0

      this.titleList = [] //程序化标题
      this.creatives.forEach( creative => {
        creative.materials = []
      });

    },
    titleList:function (params) {
      this.$emit('update:staticTitleList',params)
    }
  },
  methods:{
    // 切换素材
    switchMaterial(index,materialType){
      this.materialIndex = index
      this.creativesIndex = 0  // 当切换素材后，将创意变成第一位
      this.videoOrImage = materialType
    },
    // 切换创意
    tagsChange(index){
      this.creativesIndex = index
    },
    // 添加素材（打开素材库）
    addMaterial(imageMode,type,vh,replaceType){
      this.selectMaterialratio = imageMode
      this.materialType = type
      this.vhType = vh
      // 判断素材可以选择多少个
      if( replaceType === 'replace' ) this.optionalNumber = 0
      else {
        if( this.creativeMaterialMode === 'STATIC_ASSEMBLE' ){
          if( this.videoOrImage === 'image' ){
            this.optionalNumber = this.imageCreativeTotal - this.imageCreativeNumberItem
          }else {
            this.optionalNumber = this.videoCreativeTotal - this.videoCreativeNumberItem
          }
        }else {
          this.optionalNumber = this.creativeTotal - this.creativeNumber
        }
      }
      this.closeModal('material')
    },
    // 确认添加素材 (多选)
    confirmAddMaterial(materials){
      materials.forEach( (material,index) => {
        Object.assign(material,{ material_type:this.videoOrImage })   // 作最后一步 程序化 判断 视频图片
        if( index === 0 ){
          this.creatives[this.materialIndex].materials[this.creativesIndex].materialItem = material
        }else {
          let tags = {
            titleList:[],
            tagsName:'创意'+(this.creatives[this.materialIndex].materials.length + 1),
            materialItem:material,
          }
          this.creatives[this.materialIndex].materials.push(tags)
          if( this.creativeMaterialMode === 'STATIC_ASSEMBLE' ){
            if( this.videoOrImage === 'image' ){
              if(this.imageCreativeNumberItem === this.imageCreativeTotal) return this.$message.error(`${ material.filename } 超出限制，添加创意不成功`);
              this.$emit('update:imageCreativeNumber',++this.imageCreativeNumberItem)
            }else {
              if(this.videoCreativeNumberItem === this.videoCreativeTotal) return this.$message.error(`${ material.filename } 超出限制，添加创意不成功`);
              this.$emit('update:videoCreativeNumber',++this.videoCreativeNumberItem)
            }
          }else {
            if( this.creativesNumberItem >= this.creativeTotal ) return this.$message.error(`${ material.filename } 超出限制，添加创意不成功`);
            ++this.creativesNumberItem
          }
        }
      });

    },
    // 视频封面库
    replaceCover(video,vh,tagsIndex){
      if( Object.keys(video).length === 0 ) return this.$Tip('请先选择视频素材')
      this.vhType = vh
      this.videoConf = video
      this.closeModal('cover')
    },
    // 确认更改视频封面
    confirmReplaceCover(coverImage){
      this.creatives[this.materialIndex].materials[this.creativesIndex].coverImage = coverImage
    },
    // 关闭素材库/视频封面
    closeModal(type){
      if(type === 'material') this.is_selectMaterial = !this.is_selectMaterial
      if(type === 'cover') this.is_videoCover = !this.is_videoCover
    },
    // 添加、删除（创意）标签
    addCreative(targetKey, actionType){
      if(this.creativeMaterialMode === 'STATIC_ASSEMBLE' && actionType === 'add'){
        if( this.videoOrImage === 'image' ){
          if(this.imageCreativeNumberItem === this.imageCreativeTotal) return alert('图片超出')
          this.$emit('update:imageCreativeNumber',++this.imageCreativeNumberItem)
        }else {
          if(this.videoCreativeNumberItem === this.videoCreativeTotal){ return alert('视频超出') }
          this.$emit('update:videoCreativeNumber',++this.videoCreativeNumberItem)
        }
      }

      if( actionType === 'add'){ 
        if( this.creativesNumberItem >= this.creativeTotal ){ return alert('创意超出') }
        ++this.creativesNumberItem
        let tags = {
          tagsName:'创意'+(this.creatives[this.materialIndex].materials.length + 1),
          materialItem:{},
          titleList:[]
        }
        this.creatives[this.materialIndex].materials.push(tags)
      }else if(actionType === 'remove') {
        --this.creativesNumberItem
        if( this.videoOrImage === 'image' ){
          this.$emit('update:imageCreativeNumber',--this.imageCreativeNumberItem)
        }else {
          this.$emit('update:videoCreativeNumber',--this.videoCreativeNumberItem)
        }
        this.creatives[this.materialIndex].materials.splice(targetKey,1)
      }
      
    },
    // 添加标题(自定义)
    addTitle(){
      if( this.titleValue.trim().length === 0 ) return this.titleValue = ''
      let strWidth = this.$getStringWidth(this.titleValue)
      if( strWidth < 10 || strWidth > 60 ) return (this.$message.error('创意标题长度为5-30个字, 请正确输入') , false) 

      if( this.creatives[this.materialIndex].materials[this.creativesIndex].titleList !== 'undefined'){
        delete this.creatives[this.materialIndex].materials[this.creativesIndex].titleList
      }
      this.creatives[this.materialIndex].materials[this.creativesIndex].titleList = [this.titleValue]
      this.titleValue = ''
    },
    // 添加标题(程序化)
    addTitles(){
      let strWidth = this.$getStringWidth(this.titleValue)
      if( strWidth < 10 || strWidth > 60 ) return (this.$message.error('创意标题长度为5-30个字, 请正确输入') , false)

      if(this.titleList.length !== 10){
        this.titleList.push(this.titleValue)
        this.titleValue = ''
      }
    },
    // 删除标题 （程序化）
    deleteTitles(index){
      this.titleList.splice(index,1)
    },
    // 检测是否有创意素材未填写
    findCreativErr( ){
      this.cardErr = { 0:[], 1:[], 2:[], 3:[], 4:[] }
      this.creatives.forEach((creative,index )=> {
        if( creative.materials.length === 0 ) { return } // 如果当前创意类型内没有创意，结束本次循环
        // 判断程序化     
        if( this.creativeMaterialMode === 'STATIC_ASSEMBLE' ){
          creative.materials.forEach((material,idx) => {
            if( Object.keys(material.materialItem).length !== 0 ){
              if( material.materialItem.material_type === 'video' ){
                if( material.tagsName !== '' && this.titleList.length !== 0 && material.coverImage && Object.keys(material.coverImage).length !== 0 ) return
              }else {
                if( material.tagsName !== '' && this.titleList.length !== 0 ) return
              }
            }
            this.cardErr[index].push(idx)
          });
        }else {
          creative.materials.forEach((material,idx) => {
            if( Object.keys(material.materialItem).length !== 0 ){
              if( material.materialItem.material_type === 'video' ){
                if( material.tagsName !== '' && material.titleList.length !== 0 && material.coverImage && Object.keys(material.coverImage).length !== 0 ) return
              }else {
                if( material.tagsName !== '' && material.titleList.length !== 0 ) return
              }
            }
            this.cardErr[index].push(idx)
          });
        }
      });
    }
  }
}
</script>

<style lang="less" scoped>
  .select_material{
    .mx-box_size(200px,140px);
    margin: 20px;
    position: relative;
    border-radius: 5px;
    border: 1px solid #F8F8F9;
  }
  img{
    .mx-box_size(100%,100%);
  }
  .no-materials{
    .mx-box_size(100%,150px);
    text-align: center;
    line-height: 150px;
    border: 1px solid #DCDEE2;
  }
  // 广告素材设置
  .creativeSetup{
    padding:20px;
    .display-flex{
      display: flex;
      margin-bottom: 10px;
      .card{
        position: relative;
        margin-right: 10px;
        .card-err{
          font-size:16px;
          color:red;
          position: absolute;
          bottom: 2px;
          right: 2px;
        }
        .mx-box_size(100px,80px);
        border: 1px solid #C2C2C3;
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;
        img{
          .mx-box_size(40px,40px);
          margin-top: 10px;
        }
        .card-compute-num{
          .mx-box_size(20px,20px);
          text-align: center;
          line-height: 20px;
          color: white;
          position: absolute;
          right: -5px;
          top: -5px;
          background-color: red;
          border-radius: 50%;
        }
      }
      .activ-card{
        .card-name{
          color: @theme-color1;
        }
        border: 1px solid @theme-color1;
      }
      .card:hover{
        cursor:pointer;
        .card-name{
          color: @theme-color1;
        }
        border: 1px solid @theme-color1;
      }
    }
    // 广告素材设置内容
    .creativeSetup-content{
      width: 100%;
      margin-top: 10px;
      ::v-deep .ant-tabs-extra-content{
        .mx-box_size(50px,50px);
      }
      // 素材
      .creativeSetup-content-material{
        width: 100%;
        border: 1px solid #C2C2C3;
        // 视频素材
        .material-video{
          margin-bottom: 10px;
          display: flex;
          .video-dome,.video-cover{
           .select_material();
          }
          .video-btn{
            .mx-dom_center();
          }
        }
        // 图片素材
        .material-image{
          .select_material();
          .image-btn{
            .mx-dom_center();
          }
        }
      }
      // 标题
      .ivu-collapse-item{
        margin: 10px 0;
        .ivu-collapse-item-title{
          padding: 5px 10px;
          display: flex;
          justify-content: center;
          background-color: #F0F2F5;
          border: 1px solid #C2C2C3;
        }
      }
    }
  }
</style>